package com.hanson.common.util;


import com.hanson.common.bean.HaiBaiBean;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.TextAttribute;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.AttributedString;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

public class ImageUtil {
    private static int imageWidth = 1080;// 图片的宽度

    private static int imageHeight = 1920;// 图片的高度

    private static String imageToOss(String isLocal, BufferedImage bufferedImage) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", os);
        InputStream input = new ByteArrayInputStream(os.toByteArray());
        String url = FileUploadUtil.upload(isLocal, String.format("QR%s.jpg", UUID.randomUUID().toString()), input);
        os.close();
        input.close();
        return url;
    }

    public static BufferedImage createImg3(HaiBaiBean haiBaiBean) throws IOException {
        BufferedImage image = new BufferedImage(imageWidth, imageHeight,
                BufferedImage.TYPE_INT_RGB);

        Graphics2D g = image.createGraphics();
        g.fillRect(0, 0, imageWidth, imageHeight);
        ClassPathResource resource = new ClassPathResource("bg3.jpg");
        BufferedImage bgImage = ImageIO.read(resource.getInputStream());
        g.drawImage(bgImage, 0, 0, bgImage.getWidth(), bgImage.getHeight(), null);
        g = (Graphics2D) image.getGraphics();

        URL url2 = new URL(haiBaiBean.getUserImage());
        InputStream in2 = url2.openConnection().getInputStream();
        BufferedImage image2 = ImageIO.read(in2);
        image2 = roundImage(image2, image2.getWidth(), image2.getWidth());
        g.drawImage(image2, 470, 150, 150, 150, null);
        g = (Graphics2D) image.getGraphics();

        // 计算文字长度，计算居中的x点坐标
        g.setColor(Color.BLACK);
        Font font1 = new Font("黑体", Font.BOLD, 32);
        g.setFont(font1);
        g.drawString(haiBaiBean.getUserName(), getCenterX(g, font1, haiBaiBean.getUserName()), 350);

        g = (Graphics2D) image.getGraphics();
        Font font2 = new Font("黑体", Font.BOLD, 32);
        g.setColor(Color.BLACK);
        g.setFont(font2);
        g.drawString("优选商品，为你推荐",  getCenterX(g, font2, "优选商品，为你推荐"), 450);

        URL url4 = new URL(haiBaiBean.getGoodsImage());
        InputStream in4 = url4.openConnection().getInputStream();
        BufferedImage image4 = ImageIO.read(in4);
        g.drawImage(image4, 360, 700, 400, 400, null);

        g = (Graphics2D) image.getGraphics();
        Font font3 = new Font("黑体", Font.BOLD, 32);
        g.setColor(Color.BLACK);
        g.setFont(font3);
        String info = haiBaiBean.getGoodsName();
        FontRenderContext frc = g.getFontRenderContext();
        g.getFontRenderContext();
        java.awt.geom.Rectangle2D stringBounds = font3.getStringBounds(info, frc);
        double fontWidth = stringBounds.getWidth();
        List<String> line_list = new ArrayList<>();
        if (fontWidth <= imageWidth-200) {
            line_list.add(info);
        } else {
            int text_width = imageWidth-200;//输出文本宽度,这里就以画布宽度作为文本宽度测试
            double bs = fontWidth / text_width;//文本长度是文本框长度的倍数
            int line_char_count = (int) Math.ceil(info.length() / bs);//每行大概字数
            int begin_index = 0;
            while (begin_index < info.length()) {
                int end_index = begin_index + line_char_count;
                if (end_index >= info.length()) {
                    end_index = info.length();
                }
                String line_str = info.substring(begin_index, end_index);
                java.awt.geom.Rectangle2D tempStringBounds = font3.getStringBounds(line_str, frc);
                int tzcs = 0;//调整次数
                int tzzs = 1;//调整字数,临时文本的字符串长度大于要求的文本宽度时,每次减少临时文本的字数,然后重新测量文本宽度
                while (tempStringBounds.getWidth() > text_width) {
                    line_str = line_str.substring(0, line_str.length() - tzzs);//每次向前 tzzs 个字符重新计算(待优化)
                    tempStringBounds = font3.getStringBounds(line_str, frc);
                    tzcs++;
                }
                line_list.add(line_str);
                begin_index = begin_index + line_str.length();
            }
        }
        int y = 1180;
        for (String line : line_list) {
            g.drawString(line, getCenterX(g,font3,line), y);
            y += 50;
        }

        g.drawImage(haiBaiBean.getQrImage(), 130, 1460, 300, 300, null);
        return image;
    }

    public static BufferedImage createImg2(HaiBaiBean haiBaiBean) throws IOException {
        BufferedImage image = new BufferedImage(imageWidth, imageHeight,
                BufferedImage.TYPE_INT_RGB);

        Graphics2D g = image.createGraphics();
        g.fillRect(0, 0, imageWidth, imageHeight);
        ClassPathResource resource = new ClassPathResource("bg2.jpg");
        BufferedImage bgImage = ImageIO.read(resource.getInputStream());
        g.drawImage(bgImage, 0, 0, bgImage.getWidth(), bgImage.getHeight(), null);
        g = (Graphics2D) image.getGraphics();

        URL url4 = new URL(haiBaiBean.getGoodsImage());
        InputStream in4 = url4.openConnection().getInputStream();
        BufferedImage image4 = ImageIO.read(in4);
        g.drawImage(image4, 340, 350, 400, 400, null);
        g = (Graphics2D) image.getGraphics();

        Font font3 = new Font("黑体", Font.BOLD, 32);
        g.setColor(Color.BLACK);
        g.setFont(font3);
        String info = haiBaiBean.getGoodsName();
        FontRenderContext frc = g.getFontRenderContext();
        g.getFontRenderContext();
        java.awt.geom.Rectangle2D stringBounds = font3.getStringBounds(info, frc);
        double fontWidth = stringBounds.getWidth();
        List<String> line_list = new ArrayList<>();
        if (fontWidth <= imageWidth-200) {
            line_list.add(info);
        } else {
            int text_width = imageWidth-200;//输出文本宽度,这里就以画布宽度作为文本宽度测试
            double bs = fontWidth / text_width;//文本长度是文本框长度的倍数
            int line_char_count = (int) Math.ceil(info.length() / bs);//每行大概字数
            int begin_index = 0;
            while (begin_index < info.length()) {
                int end_index = begin_index + line_char_count;
                if (end_index >= info.length()) {
                    end_index = info.length();
                }
                String line_str = info.substring(begin_index, end_index);
                java.awt.geom.Rectangle2D tempStringBounds = font3.getStringBounds(line_str, frc);
                int tzcs = 0;//调整次数
                int tzzs = 1;//调整字数,临时文本的字符串长度大于要求的文本宽度时,每次减少临时文本的字数,然后重新测量文本宽度
                while (tempStringBounds.getWidth() > text_width) {
                    line_str = line_str.substring(0, line_str.length() - tzzs);//每次向前 tzzs 个字符重新计算(待优化)
                    tempStringBounds = font3.getStringBounds(line_str, frc);
                    tzcs++;
                }
                line_list.add(line_str);
                begin_index = begin_index + line_str.length();
            }
        }
        int y = 900;
        for (String line : line_list) {
            g.drawString(line, getCenterX(g,font3,line), y);
            y += 50;
        }

        g.drawImage(haiBaiBean.getQrImage(), imageWidth / 2-200, 1150, 400, 400, null);
        return image;
    }

    public static BufferedImage createImg1(HaiBaiBean haiBaiBean) throws IOException {
        BufferedImage image = new BufferedImage(imageWidth, imageHeight,
                BufferedImage.TYPE_INT_RGB);

        Graphics2D g = image.createGraphics();
        g.fillRect(0, 0, imageWidth, imageHeight);
        ClassPathResource resource = new ClassPathResource("bg1.jpg");
        BufferedImage bgImage = ImageIO.read(resource.getInputStream());
        g.drawImage(bgImage, 0, 0, bgImage.getWidth(), bgImage.getHeight(), null);
        g = (Graphics2D) image.getGraphics();

        URL url2 = new URL(haiBaiBean.getUserImage());
        InputStream in2 = url2.openConnection().getInputStream();
        BufferedImage image2 = ImageIO.read(in2);
        image2 = roundImage(image2, image2.getWidth(), image2.getWidth());
        g.drawImage(image2, 470, 150, 150, 150, null);
        g = (Graphics2D) image.getGraphics();

        // 计算文字长度，计算居中的x点坐标
        g.setColor(Color.BLACK);
        Font font1 = new Font("黑体", Font.BOLD, 32);
        g.setFont(font1);
        g.drawString(haiBaiBean.getUserName(), getCenterX(g, font1, haiBaiBean.getUserName()), 350);

        g = (Graphics2D) image.getGraphics();
        Font font2 = new Font("黑体", Font.BOLD, 32);
        g.setColor(Color.BLACK);
        g.setFont(font2);
        g.drawString("优选商品，为你推荐",  getCenterX(g, font2, "优选商品，为你推荐"), 450);

        URL url4 = new URL(haiBaiBean.getGoodsImage());
        InputStream in4 = url4.openConnection().getInputStream();
        BufferedImage image4 = ImageIO.read(in4);
        g.drawImage(image4, 360, 700, 400, 400, null);

        g = (Graphics2D) image.getGraphics();
        Font font3 = new Font("黑体", Font.BOLD, 32);
        g.setColor(Color.BLACK);
        g.setFont(font3);

        String info = haiBaiBean.getGoodsName();
        FontRenderContext frc = g.getFontRenderContext();
        g.getFontRenderContext();
        java.awt.geom.Rectangle2D stringBounds = font3.getStringBounds(info, frc);
        double fontWidth = stringBounds.getWidth();
        List<String> line_list = new ArrayList<>();
        if (fontWidth <= imageWidth / 2) {
            line_list.add(info);
        } else {
            int text_width = imageWidth / 2;//输出文本宽度,这里就以画布宽度作为文本宽度测试
            double bs = fontWidth / text_width;//文本长度是文本框长度的倍数
            int line_char_count = (int) Math.ceil(info.length() / bs);//每行大概字数
            int begin_index = 0;
            while (begin_index < info.length()) {
                int end_index = begin_index + line_char_count;
                if (end_index >= info.length()) {
                    end_index = info.length();
                }
                String line_str = info.substring(begin_index, end_index);
                java.awt.geom.Rectangle2D tempStringBounds = font3.getStringBounds(line_str, frc);
                int tzcs = 0;//调整次数
                int tzzs = 1;//调整字数,临时文本的字符串长度大于要求的文本宽度时,每次减少临时文本的字数,然后重新测量文本宽度
                while (tempStringBounds.getWidth() > text_width) {
                    line_str = line_str.substring(0, line_str.length() - tzzs);//每次向前 tzzs 个字符重新计算(待优化)
                    tempStringBounds = font3.getStringBounds(line_str, frc);
                    tzcs++;
                }
                line_list.add(line_str);
                begin_index = begin_index + line_str.length();
            }
        }
        int y = 1400;
        for (String line : line_list) {
            g.drawString(line, 100, y);
            y += 50;
        }
        g = (Graphics2D) image.getGraphics();
        g.setFont(new Font("黑体", Font.PLAIN, 32));
        g.setColor(Color.RED);
        g.drawString("￥"+haiBaiBean.getPrice(), 100, y + 20);

        g = (Graphics2D) image.getGraphics();
        g.setColor(Color.GRAY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        AttributedString as = new AttributedString("原价￥"+haiBaiBean.getOldPrice());
        as.addAttribute(TextAttribute.FONT, new Font("黑体", Font.PLAIN, 36));
        as.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
        g.drawString(as.getIterator(), 100, y + 90);

        g = (Graphics2D) image.getGraphics();
        g.drawImage(haiBaiBean.getQrImage(), imageWidth / 2 + 150, 1350, 310, 300, null);
        return image;
    }

    private static BufferedImage roundImage(BufferedImage image, int targetSize, int cornerRadius) {
        BufferedImage outputImage = new BufferedImage(targetSize, targetSize, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = outputImage.createGraphics();
        g2.setComposite(AlphaComposite.Src);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(Color.WHITE);
        g2.fill(new RoundRectangle2D.Float(0, 0, targetSize, targetSize, cornerRadius, cornerRadius));
        g2.setComposite(AlphaComposite.SrcAtop);
        g2.drawImage(image, 0, 0, null);
        g2.dispose();
        return outputImage;
    }

    /**
     *  * HEX颜色 转 RGB颜色
     *  *
     *  * @param hex
     *  * @return
     *  
     */
    public static RGB toRGB(String hex) {
        RGB rgb = new RGB();
        if (!Pattern.matches("^#[0-9a-f[A-F]]{6}", hex)) {
            return rgb;
        }
        String redStr = hex.substring(1, 3);
        String greenStr = hex.substring(3, 5);
        String blueStr = hex.substring(5);
        rgb.red = Integer.valueOf(redStr, 16).intValue();
        rgb.green = Integer.valueOf(greenStr, 16).intValue();
        rgb.blue = Integer.valueOf(blueStr, 16).intValue();
        return rgb;
    }

    public static int getCenterX(Graphics2D g, Font font, String text) {
        FontMetrics fm = g.getFontMetrics(font);
        int textWidth = fm.stringWidth(text);
        return (imageWidth - textWidth) / 2;
    }
}
